package search;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import net.barashev.seclub.io.DataMarshaller;
import net.barashev.seclub.io.IteratingSlot;
import net.barashev.seclub.io.OutputSlot;
import net.barashev.seclub.io.marshaller.IntegerMarshaller;

public class Sorter {
	private final String RANKS = "linkRank";
	private final String RANKS_OF_OUR = "OurLinkRank";
	private final int bufferSize = 1024;//must be even
	private int idx;
	private IteratingSlot<?, ? extends DataMarshaller<?>> rankFileSlot;
	private OutputSlot<Integer, ? extends DataMarshaller<Integer>> rankSubFileSlot;

	public List<Integer> sort(DiscBufferedIntegerList toSort, int maxResSize)
			throws IOException {
		/*rankFileSlot = toSort.getBufferMgr().allocateIteratingSlot(bufferSize,
				toSort.getFileMgr().getFile(RANKS));
		rankSubFileSlot = toSort.getBufferMgr().allocateOutputSlot(
				toSort.getFileMgr().createFile(RANKS_OF_OUR,
						new IntegerMarshaller()));
		idx=0;
		while (toSort.hasNext()) {
			int Id = toSort.readNext();
			rankSubFileSlot.append(Id);
			rankSubFileSlot.append(getWeight(Id, rankFileSlot));
		}
		rankFileSlot.release();
		rankSubFileSlot.release();
		rankFileSlot=toSort.getBufferMgr().allocateIteratingSlot(bufferSize,
				toSort.getFileMgr().getFile(RANKS_OF_OUR));
		*/
		//TODO stub for test
		LinkedList<Integer>res=new LinkedList<Integer>();
		toSort.makeReadable();
		while(toSort.hasNext()){
			res.addLast(toSort.readNext());
		}
		return res;
	}

	private int getWeight(int id,
			IteratingSlot<?, ? extends DataMarshaller<?>> slot) {
		int currId=0;
		while(currId<id&idx<slot.getBlockCount()){
			currId=(Integer)slot.getBlock(idx).get(0);
			idx+=2;
		}
		idx--;
		if(idx<slot.getBlockCount()){
			return (Integer)slot.getBlock(idx).get(0);
		}else{
		return 0;
		}
	}
}
